package net.yebaihe.buildapp;

import java.io.File;

import net.yebaihe.sdk.HttpConnection;
import net.yebaihe.sdk.LilysdkActivity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class ChooseTemplate extends Activity {
	
	class MySimpleCursorAdapter extends SimpleCursorAdapter{

		public MySimpleCursorAdapter(Context context, int layout, Cursor c,
				String[] from, int[] to) {
			super(context, layout, c, from, to);
		}
		
		@Override
		public void bindView(View view, Context context, Cursor cursor) {
		    super.bindView(view, context, cursor);
		    Button b=(Button) view.findViewById(R.id.iddowndemo);
		    b.setTag(cursor.getString(2));
		    b.setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View arg0) {
					startDownload(arg0);
				}
		    });
		}
		
	}

	private ProgressBar progressbar;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.choosetemplate);
        
        refreshTemplateList();
        
        progressbar=(ProgressBar)this.findViewById(R.id.idprogress);
    }

    private String getOutputPath() {
		String basedir=Environment.getExternalStorageDirectory()+"/lilydownload/apks/";
		File f=new File(basedir);
		if (!f.exists()) f.mkdirs();
		return basedir+"template.apk";
	}
    
	private void startDownload(View view) {
		final Button lbtn=(Button) view;
        new HttpConnection(this,new Handler(){
        	public void handleMessage(Message message) {
        		switch (message.what) {
        		case HttpConnection.DID_START:
        			Toast.makeText(ChooseTemplate.this, "开始下载 "+lbtn.getTag(), Toast.LENGTH_LONG).show();
        			progressbar.setVisibility(View.VISIBLE);
        			break;
        		case HttpConnection.DID_SUCCEED: {
        			Intent intent = new Intent(Intent.ACTION_VIEW);
        			progressbar.setVisibility(View.GONE);
                    intent.setDataAndType(Uri.fromFile(new File
                    (getOutputPath())), "application/vnd.android.package-archive");
                    startActivity(intent); 
                    finish();
                    break;
        		}
        		case HttpConnection.DID_PROGRESS:{
        			int percent=(Integer) message.obj;
        			progressbar.setProgress(percent);
        			break;
        		}
        		}
        	}
        }).file(lbtn.getTag().toString(), getOutputPath());
	}
    
    
	private void refreshTemplateList() {
		MyHelper dbhelper = MyHelper.get(this);
		SQLiteDatabase db = dbhelper.getReadableDatabase();
		String sql="select * from template";
		Cursor result = db.rawQuery(sql, null);
        CursorAdapter adapter = new MySimpleCursorAdapter(this, R.layout.temprow,
        		result, new String[] {"name",},
                new int[] { R.id.idtitle, });
        final ListView templist=(ListView) this.findViewById(R.id.templist);
        templist.setAdapter(adapter);	
        
        templist.setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Cursor row=(Cursor) templist.getItemAtPosition(arg2);
				Intent i=new Intent(ChooseTemplate.this,FillContent.class);
				i.putExtra("tempidx", row.getInt(0));
				i.putExtra("appidx", -1);
				startActivity(i);
			}
        });
        
	}
}